import { HttpService } from '../.././services/http.service';
import { Router } from '@angular/router';
import { Md5 } from "ts-md5/dist/md5";
import { ModalController } from '@ionic/angular';
import { LoginInfoService } from '../../services/login-info.service';
import { BaseUiService } from '../../services/base-ui.service';
import { Component, ElementRef, ViewChild } from '@angular/core';
import {EventService  } from '../../services/QaService';
@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage{
  greetDiv: ElementRef;
  public username:any
  public username1:any
  public password:any
  public isShow:any=true
  public birthday: any
  public idcard:any
  public phoneNum:any
  public gender:any
  public verifyNum:any
  public pwdNum:any
  public pwdNum1:any
  public tabsNum:any=1
  public yzmCode:any = true
  public international:any = '1' //国内外电话
  //验证码倒计时 全局定义变量
  public verifyCode: any ={
    verifyCodeTips: "获取验证码",
    countdown: 60,//总共时间
    disable: true
  };
  
  public eye = 'password'
  public flag:boolean;
  public onlineTab = "tab1"
  public sexlist:any = [
    {
      name:'男',
      value: 1
    },
    {
      name:'女',
      value: 0
    }
  ]

  constructor(
    private elementRef: ElementRef,
    public modalController:  ModalController,
    public BaseUiService:  BaseUiService,
    public HttpService: HttpService,
    public router: Router,
    public LoginInfoService: LoginInfoService,
    public eventService:EventService
  ) {
      window.localStorage.clear();
      this.eventService.eventEmitter.emit('loginEvent');    //通知用户中心更新用户信息
   }

         
  ngOnInit() {
    this.flag = this.LoginInfoService.getlocal('isFlag');
    if(this.flag){
      this.username = this.LoginInfoService.getlocal('loginusername')
    }
  }
  subHeaderChange(id:any){  
    this.tabsNum=id;   //tabs选中
  }
  remember() {
    this.flag = !this.flag;
  }
  show() {
    if (this.eye == 'text') {
      this.eye = 'password'
      this.isShow = false
    } else {
      this.eye = 'text'
      this.isShow = true
    }

  }

  //验证码登录
  loginByCode(){

    let user = /^[a-zA-Z0-9]+$/;
    if (!this.username) {
      this.BaseUiService.showToast("登录名不能为空!",'customred','top');
      return;
    } else if (!this.verifyNum) {
      this.BaseUiService.showToast("验证码不能为空!",'customred','top');
    }else if (!user.test(this.username)) {
      this.BaseUiService.showToast("用户名格式不正确,请输入(字母，数字，下划线，减号)",'customred','top');
    }else {
      let fromData = {
        mobile: this.username,
        smsCode: this.verifyNum,
        source: 1
      };
      this.HttpService.authCodeApp(fromData).then(
        res => {
          console.log(res, 1252)
          if (res["code"] == '200') {
            this.LoginInfoService.setlocal('isFlag', this.flag);
            this.LoginInfoService.setInfo(res["items"]);
            this.eventService.eventEmitter.emit('loginEvent');    //通知用户中心更新用户信息
            this.modalController.getTop().then(event => {
              event.dismiss({
                test:"11"
              },"test");
            })
            if(this.flag){
              this.LoginInfoService.setlocal('loginusername',this.username) 
            }
            //如果没有实名
            if(res["items"].user.userName == ''){
              this.router.navigate(['/mycenter/verified'])
            }
          }else{
            this.BaseUiService.showToast(res['msg'],'customred','top');
          }
        }
      ).catch(err=>{
        this.BaseUiService.showToast(err,'customred','top');
      })
    }
  }
  
  login() {
    console.log(132)
    let user = /^[a-zA-Z0-9]+$/;
    // 密码正则,输入6-16位字母和数字组合
    let pwd = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
    // var pwd = /^\d{6,20}$/;
    // 开始验证
    // 用户名为空给出提示 或者  密码为空给出提示
    if (!this.username) {
      this.BaseUiService.showToast("登录名不能为空!",'customred','top');
      return;
    } else if (!this.password) {
      this.BaseUiService.showToast("密码不能为空!",'customred','top');
    }else if (!user.test(this.username)) {
      this.BaseUiService.showToast("用户名格式不正确,请输入(字母，数字，下划线，减号)",'customred','top');
    } else if (!pwd.test(this.password)) {
      this.BaseUiService.showToast("密码格式不正确,请输入6-16数字",'customred','top');
    }else {
      let fromData = {
        loginName: this.username,
        password: Md5.hashStr(this.password),
        source: 1
      };
      console.log(fromData)
      this.HttpService.login(fromData).then(
        res => {
          console.log(res, 1252)
          if (res["code"] == '200') {
            this.LoginInfoService.setlocal('isFlag', this.flag);
            // this.LoginInfoService.setlocal('user',res["items"].user)
            // this.LoginInfoService.setlocal('token',res["items"].token)
            this.LoginInfoService.setInfo(res["items"]);
            this.eventService.eventEmitter.emit('loginEvent');    //通知用户中心更新用户信息
            this.modalController.getTop().then(event => {
              event.dismiss({
                test:"11"
              },"test");
            })
            if(this.flag){
              this.LoginInfoService.setlocal('loginusername',this.username) 
            }
          }else{
            this.BaseUiService.showToast(res['msg'],'customred','top');
          }
        }
      ).catch(err=>{
        console.log(err,'+++++++++---------------------------++++++++++++')
        this.BaseUiService.showToast(err,'customred','top');
      })
    }
  }
  //注册
  getRegister(){
    console.log(this.international)
    let idcardZ = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    // // 密码正则,输入6-16位字母和数字组合
    let pwdZ = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
    // // var pwd = /^\d{6,20}$/;
    if(!this.phoneNum){
      return  this.BaseUiService.showToast("请输入手机号",'customred','top');
    }else if (!pwdZ.test(this.pwdNum)){
      return this.BaseUiService.showToast("密码格式不对,请输入6位到20位的字母加数字",'customred','top');
    }else if (this.pwdNum1 !== this.pwdNum ){
      return this.BaseUiService.showToast("两次密码不一致",'customred','top');
    }else{
      // this.getInfoByIdNo(this.idcard);
      console.log(this.international)
    if(this.international == '1'){
      let p = {
        userName: this.username1,
        mobile: this.phoneNum,
        password: Md5.hashStr(this.pwdNum),
        idCard: this.idcard,
        birthday: this.birthday,
        gender: this.gender,
        smsCode: this.verifyNum,
        mobileType: this.international,
      }
      this.HttpService.register(p).then(res => {
        if(res["code"]==200){
          // this.yzmCode=false
          this.verifyNum=''
          this.idcard=''
          this.pwdNum=''
          this.phoneNum=''
          this.tabsNum=1
          this.yzmCode=true
        }else{
          this.BaseUiService.showToast(res['msg'],'customred','top');
        }
      })
    }else{
      this.verifyNum = ''
      let p = {
        userName: this.username1,
        mobile: this.phoneNum,
        password: Md5.hashStr(this.pwdNum),
        idCard: this.idcard,
        birthday: this.birthday,
        gender: this.gender,
        mobileType: this.international,
      }
      this.HttpService.register(p).then(res => {
        if(res["code"]==200){
          // this.yzmCode=false
          this.verifyNum=''
          this.idcard=''
          this.pwdNum=''
          this.phoneNum=''
          this.tabsNum=1
          this.BaseUiService.showToast('注册成功，请等待1-3日内后台审核，','customblue','top');
          this.yzmCode=true
        }else{
          this.BaseUiService.showToast(res['msg'],'customred','top');
        }
      })
    }
    
    }
  }

  //根据身份证号截取生日
  getInfoByIdNo(UUserCard){
      let id = UUserCard.toString() 
      //获取出生日期
      this.birthday = id.substring(6, 10) + "-" + id.substring(10, 12) + "-" + id.substring(12, 14);
      //获取性别
      if (parseInt(id.substr(16, 1)) % 2 == 1) {
        //男
        this.gender =  1;
      } else {
        //女
        this.gender = 0;
      }
  }

  getCodeVerify(){
    //点击时判断有没有输入
    if(this.username==undefined){
      this.BaseUiService.showToast("手机号不能为空",'customred','top');
    }else if(!(/^1[3456789]\d{9}$/.test(this.username))){
      this.BaseUiService.showToast("请输入正确手机号",'customred','top');
    }else{
    //每次点击时初始化
      this.verifyCode = {
          verifyCodeTips: "获取验证码",
          countdown: 60,//总共时间
          disable: true //禁止按钮被点击
      }
      this.settime()
        let p = {
        mobile:this.username,
        SmsCode: 1
      }
      this.HttpService.get_verify(p).then(res => {
        if(res["code"]==200){
          this.yzmCode=false
        }else{
          this.BaseUiService.showToast("获取验证码失败！",'customred','top');
        }
      })
    }
  }

  //获取验证码的方法
  getVerify(){
    //点击时判断有没有输入
    if(this.phoneNum==undefined){
      this.BaseUiService.showToast("手机号不能为空",'customred','top');
    }else if(!(/^1[3456789]\d{9}$/.test(this.phoneNum))){
      this.BaseUiService.showToast("请输入正确手机号",'customred','top');
    }else{
    //每次点击时初始化
    this.verifyCode = {
        verifyCodeTips: "获取验证码",
        countdown: 60,//总共时间
        disable: true //禁止按钮被点击
    }
    this.settime()
      let p = {
      mobile:this.phoneNum,
      SmsCode: 1
    }
    this.HttpService.get_verify(p).then(res => {
      if(res["code"]==200){
        this.yzmCode=false
      }else{
        this.BaseUiService.showToast("获取验证码失败！",'customred','top');
      }
    })
  }
  }

//倒计时
settime() {
  if(this.verifyCode.countdown == 0) {
    this.verifyCode.verifyCodeTips = "获取验证码";
    this.verifyCode.disable = true;
    return;
  } else {
    this.verifyCode.countdown--;
    this.verifyCode.disable = false;
  }
  setTimeout(() => {
    this.verifyCode.verifyCodeTips = "重新获取" + this.verifyCode.countdown + "秒";
    this.settime();
  }, 1000);
}

closeModal(){
  this.modalController.getTop().then(event => {
    event.dismiss({
      test:"11"
    },"test");
  })
}

//找回密码
goForget(){
  this.modalController.getTop().then(event => {
    event.dismiss({
      test:"11"
    },"test");
  })
  this.router.navigate(['/mycenter/forgetpwd'])
}

}


// export class SegmentExample {
//   segmentChanged(ev: any) {
//     console.log('Segment changed', ev);
//   }
// }